home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 18484 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: news.halcyon.com!usenet
  2. From: normanb@halcyon.com (Norm Bryar)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Calling the wrong constructor
  5. Date: Sat, 20 Apr 1996 15:10:08 GMT
  6. Organization: Northwest Nexus Inc.
  7. Message-ID: <4laun2$4vm@news.halcyon.com>
  8. References: <4kot87$796@earth.njcc.com> <Andrew_Carol-1804962001240001@17.127.18.252>
  9. NNTP-Posting-Host: blv-pm2-ip16.halcyon.com
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. Andrew_Carol@quickmail.apple.com (Andrew) wrote:
  13.  
  14. >In article <4kot87$796@earth.njcc.com>, mike@pluto.njcc.com (Michael
  15. >Hohenshilt) wrote:
  16.  
  17. >>   This might seem like a basic question, but lets say you something set u 
  18. >> like the following:
  19. >> 
  20. >> class Parent { Parent() { allocsomething} ~Parent() { deletesomething }... };
  21. >> class Foo : Parent { Foo() { allocsomething } ~Foo() {deletesomething }... };
  22. >> class Contain { Parent *ptr; ... };
  23. >> 
  24. >> both parent, and foo allocate memory, and will free it up when being 
  25. >> destructed.  Contain just holds a pointer of type Parent, and its 
  26. >> constructor takes such a pointer as a parameter.
  27. >>   If I store a pointer of type Foo into contain.ptr and discard that 
  28. >> pointer.  Is there any way to have contain (via destructors) free up all 
  29. >> memory allocated by Foo and/or Parent?
  30.  
  31.  
  32. >Assuming that "Contain" keeps a copy of the 'ptr'...
  33.  
  34. >~Contain() { delete ptr; }
  35.  
  36. >This will call the destructor of Foo and Parent...
  37.  
  38. >Good luck!
  39.  
  40. No, it won't.  
  41. Your Parent class needs virtual ~Parent().  Then it will.
  42.  
  43. IMHO, you can never be sure how people after you will maintain your
  44. code, perhaps deriving classes from your own and calling functions
  45. that depend on polymorphism.  Therefore, always make your destructor
  46. virtual.  
  47.  
  48. If you don't want the overhead of a vtable per object, make this
  49. decision not to use virtuals a well published, much heralded fact in
  50. your header.  (Again, IMHO).
  51.  
  52.                     --Norm 
  53.  
  54.